package com.cuitrip.business.home.trip;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.bill.AccountAddEvent;
import com.cuitrip.business.home.trip.ui.TripItemHolderView;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.tripservice.TripEditActivity;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.JumpSuccessUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.adapter.BaseHolderView;
import com.lab.adapter.HolderViewAdapter;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.ArrayUtil;
import com.lab.utils.MessageUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created on 7/23.
 */
public class TripServiceListFragment extends CustomUiFragment implements SwipeRefreshLayout.OnRefreshListener, IProxyCallback {

    public static final String TRIP_SERVICE_STATUS_CHANGED = "ct_trip_service_status_changed";
    public static final int TYPE_VALIDATE_ALL=3;
    public static final int REQUEST_CODE_COMPLETE_POP=0x01;



    @Bind(R.id.state_layout)
    StateLayout mStateLayout;
    @Bind(R.id.check_hint)
    LinearLayout mCheckHintLayout;

    private SwipeRefreshLayout refresh;
    private ListView mListView;
    private List<ServiceInfo> mServices = new ArrayList<>();
    private HolderViewAdapter holderViewAdapter;
    private ApiProxy mApiProxy = new ApiProxy(this);
    private BroadcastReceiver mOrderStatusChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (TRIP_SERVICE_STATUS_CHANGED.equals(intent.getAction())) {
                refresh.setRefreshing(true);
                refreshList();
            }

        }
    };
    private CtUserInfo userInfo;
    private List<ServiceInfo> serviceInfos;

    /**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     * 分页
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return super.onCreateView(inflater, container, savedInstanceState, R.layout.ct_finder_service_list);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this, getView());
        mStateLayout.setEmptyLayoutID(R.layout.home_empty_insider_layout);
        mListView = (ListView) getView().findViewById(R.id.ct_list);
        mListView.addHeaderView(View.inflate(getHostActivity(), R.layout.ct_list_padding_header, null));
        refresh = (SwipeRefreshLayout) getView().findViewById(R.id.refresh_layout);
        holderViewAdapter = new HolderViewAdapter(getActivity(), mServices, TripItemHolderView.class);
        mListView.setAdapter(holderViewAdapter);
        holderViewAdapter.setHolderViewCallback(new HolderViewAdapter.HolderViewCallback() {
            @Override
            public void onHolderViewInvalidate(BaseHolderView holderView, int position) {
                if (holderView instanceof TripItemHolderView) {
                    ((TripItemHolderView) holderView).setOnDataChangeCallBack(new TripItemHolderView.OnDataChangeCallBack() {
                        @Override
                        public void onDataRemove(ServiceInfo serviceInfo) {
                            deleteService(serviceInfo.getSid());
                        }
                    });
                }
            }
        });
    }

    @Override
    public void initData() {
        refresh.setEnabled(true);
        refresh.setRefreshing(true);
        refreshList();


    }

    @OnClick(R.id.check_hint)
    public void jump2Verify(){
        int type = checkUserInfo();
        if (serviceInfos!=null) {
            JumpSuccessUtil.navigete2CompletInsiderInfoPage(TripServiceListFragment.this, serviceInfos.get(0), userInfo, type, REQUEST_CODE_COMPLETE_POP);
        }

    }

    @Override
    public void initListener() {
        refresh.setOnRefreshListener(TripServiceListFragment.this);
        mStateLayout.setAction(new StateLayout.Action() {
            @Override
            public void performEmptyAction() {
                if (getActivity() != null) {
                    TripEditActivity.navigate2CreateTripActivity(getHostActivity(),true);

                }
            }
        });
        mStateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                mStateLayout.changeState(StateLayout.State.Loading);
                refreshList();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        TrackUtil.trackScreenName("/insider/trips");
    }


    private int checkUserInfo(){
        int type=-1;
        CtUserInfo ctUserInfo = LoginInstance.getInstance().getUserInfo();
        if (this.userInfo !=null) {
            if (!this.userInfo.isFinished()) {
                type = 0;
            } else {
                int validType = this.userInfo.getValidType();

                if ((validType & CtUserInfo.VALIDATE_MASK_PHONE)!=CtUserInfo.VALIDATE_MASK_PHONE ) {
                    //手机未验证
                    type = 1;
                } else if (CtUserInfo.ID_CHECK_NONE== ctUserInfo.getIdCheckStatus()|| CtUserInfo.ID_CHECK_FAILED== ctUserInfo.getIdCheckStatus()/*CtUserInfo.VALIDATE_MASK_IDCARD != validType && CtUserInfo.VALIDATE_MASK_INTERNATION_CARD != validType*/) {
                    //身份Id未验证
                    type = 2;
                } else {
                    //全部验证完
                    type = 3;
                }
            }
        }
        return type;
    }

    private void deleteService(String sid) {
        showNoCancelDialog();
        ServiceBusiness.deleteServiceInfo(mApiProxy,sid);
    }

    private void inflateList(List<ServiceInfo> serviceInfos){
        if (ArrayUtil.isNullOrEmpty(serviceInfos)) {
            mStateLayout.changeState(StateLayout.State.Empty);
            refresh.setEnabled(false);
        } else {
            mServices.clear();
            mServices.addAll(serviceInfos);
            holderViewAdapter.notifyDataSetChanged();
            mStateLayout.changeState(StateLayout.State.INIT);
            refresh.setEnabled(true);
        }
    }

    @Override
    public void onRefresh() {
        refresh.setRefreshing(true);
        refreshList();
    }

    private void refreshList(){
        ServiceBusiness.getServiceList(mApiProxy);
        OrderBusiness.checkBasicUserInfo(mApiProxy,"1");
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarMiddleAreaName = getResources().getString(R.string.main_nav_trips);
        config.mTopbarLeftAreaLeftDrawableResId = 0;
        config.mTopbarRightAreaName = getString(R.string.trip_operation_create);
        config.mRightStyle = CustomUiConfig.AreaStyle.TEXT_STYLE;
        return config;
    }

    @Override
    public void onTopbarRightPress() {
        super.onTopbarRightPress();
        if (getHostActivity() != null) {
            TripEditActivity.navigate2CreateTripActivity(getContext(),true);
//            SelectTripCatesActivity.startActivity(getHostActivity());
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (refresh != null) {
            refresh.setRefreshing(false);
        }
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter filter = new IntentFilter(TRIP_SERVICE_STATUS_CHANGED);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mOrderStatusChangedReceiver, filter);
    }

    public void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mOrderStatusChangedReceiver);
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.SERVICE_LIST.equals(response.getApiName())){
            refresh.setRefreshing(false);
            if (response.isResponseNormal()) {
                if (response.result instanceof List) {
                    serviceInfos = (List<ServiceInfo>) response.result;
                    inflateList(serviceInfos);
                }
            }else{
                if (!TextUtils.isEmpty(response.msg)) {
                    MessageUtils.showToast(response.msg);
                }
                mStateLayout.changeState(StateLayout.State.NoNetwork);
            }
        }else if (ApiManager.DELETE_SERVICE_INFO.equals(response.getApiName())){
            hideNoCancelDialog();
            if (response.isResponseNormal()) {
                refresh.setRefreshing(true);
                refreshList();
            }else{
                if (!TextUtils.isEmpty(response.msg)) {
                    MessageUtils.showToast(response.msg);
                }
            }
        }else if (ApiManager.CHECK_BASIC_USER_INFO.equals(response.getApiName())){
            if (response.isResponseNormal()){
                if (response.result instanceof CtUserInfo) {
                    userInfo = (CtUserInfo) response.result;
                    int type = checkUserInfo();
                    if (type==TYPE_VALIDATE_ALL){
                        mCheckHintLayout.setVisibility(View.GONE);
                    }else {
                        mCheckHintLayout.setVisibility(View.VISIBLE);
                    }
                }
            }else{
                if (!TextUtils.isEmpty(response.msg)) {
                    MessageUtils.showToast(response.msg);
                }
            }
        }


        return false;
    }

}
